package com.fi.recogn;

import lombok.Cleanup;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.usermodel.*;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

import static com.fi.recogn.util.FileConvertUtil.docConvertDocx;

/**
 * @Description TODO
 * @Author lujiahong
 * @Date 2025/10/18 10:31
 */
public class testforme {

    @Test
    public void execWord() throws IOException {
        readDoc(Files.newInputStream(Paths.get("D:\\ocr\\还不错.doc")));
        // readDocX(new URL("https://oss.banklaw.com.cn/misc/2025/10/17/P_UPLOAD/a50bf32094274bc3a7ae7b15c09a9f67.docx").openStream());
    }

    public static void readDoc(InputStream is) throws IOException {
        // 方式一
        @Cleanup HWPFDocument doc = new HWPFDocument(is);
        @Cleanup WordExtractor extractor = new WordExtractor(doc);
        String content = extractor.getText();
        System.out.println(content);
        // 方式二
        // @Cleanup HWPFDocument doc = new HWPFDocument(is);
        // readDocX(docConvertDocx(doc));
        // 方式三
        // @Cleanup WordExtractor extractor = new WordExtractor(is);
        // System.out.println(extractor.getText());
    }
    public static void readDocX(InputStream is) throws IOException {
        @Cleanup XWPFDocument docx = new XWPFDocument(is);
        readDocX(docx);
    }
    public static void readDocX(XWPFDocument docx) throws IOException {
        StringBuilder sb = new StringBuilder();
        for (IBodyElement bodyElement : docx.getBodyElements()) {
            if (bodyElement instanceof XWPFParagraph) {
                XWPFParagraph paragraph = (XWPFParagraph) bodyElement;
                sb.append(paragraph.getText()).append("\r\n");
            } else if (bodyElement instanceof XWPFTable) { // 如果需要提取表格中的文本
                XWPFTable table = (XWPFTable) bodyElement;
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        sb.append(cell.getText()).append("\t");
                    }
                    sb.append("\r\n");
                }
            }
        }
        String content = sb.toString();
        System.out.println(content);
    }
}